package com.pda.yuanjing.pages.sybz;

import android.app.DatePickerDialog;
import android.content.IntentFilter;
import android.graphics.Color;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.apkfuns.logutils.LogUtils;
import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.google.gson.Gson;
import com.pda.yuanjing.PDApp;
import com.pda.yuanjing.R;
import com.pda.yuanjing.beanin.JieDianBeanIn;
import com.pda.yuanjing.beanout.BDBatchBeanOut;
import com.pda.yuanjing.beanout.BDBeanOut;
import com.pda.yuanjing.beanout.BDMXBeanOut;
import com.pda.yuanjing.beanout.BaseBeanOut;
import com.pda.yuanjing.beanout.JDBeanNewOut;
import com.pda.yuanjing.beanout.PPBeanOut;
import com.pda.yuanjing.beanout.SCBeanOut;
import com.pda.yuanjing.beanout.TJBeanOut;
import com.pda.yuanjing.boardcast.CustomReceiver;
import com.pda.yuanjing.boardcast.ScannerInterface;
import com.pda.yuanjing.dialog.product.ProductAllDialog;
import com.pda.yuanjing.message.MessageBus;
import com.pda.yuanjing.pages.sybom.BomBJActivity;
import com.public_module.basemvp.activity.BaseActivity;
import com.public_module.config.ApiYJ;
import com.public_module.config.SetConfig;
import com.public_module.tools.DateUtils;
import com.public_module.tools.SharedPreferencesManger;
import com.public_module.tools.StringProcess;
import com.public_module.tools.VoiceUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.OkHttpClient;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Response;
import retrofit2.Retrofit;

public class BZActivity extends BaseActivity<PageModel, PageView, PagePresent> implements PageView {
    @BindView(R.id.iv_title_left)
    ImageView ivTitleLeft;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.tvr)
    TextView tvr;
    @BindView(R.id.rltitle)
    RelativeLayout rltitle;
    @BindView(R.id.tvb)
    TextView tvb;
    @BindView(R.id.lld)
    LinearLayout lld;
    @BindView(R.id.bt1)
    Button bt1;
    @BindView(R.id.bt2)
    Button bt2;
    @BindView(R.id.oet)
    EditText oet;
    @BindView(R.id.bt3)
    Button bt3;
    @BindView(R.id.listView)
    ListView listView;

    private String TAG = "BZActivity";
    ScannerInterface scanner;
    CustomReceiver customReceiver = null;
    VoiceUtils voiceUtils;
    private OptionsPickerView pickerView;
    JDBeanNewOut.DataBean dataBean;
    BDMXBeanOut bdmxBeanOutm;
    List<String> list = new ArrayList<>();
    ItemAdapter itemAdapter;
    boolean scanfFlag = true;
    String bdid = "";
    String bdbid = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_bz);
        ButterKnife.bind(this);
        tvTitle.setText("溯源备注 " + SharedPreferencesManger.getRealName());
        scanner = new ScannerInterface(this);
        scanner.setOutputMode(1);
        customReceiver = new CustomReceiver(
                new CustomReceiver.PListener1() {
                    @Override
                    public void setData(CustomReceiver.Dataa dataa) {
                    }
                },
                new CustomReceiver.PListener2() {
                    @Override
                    public void setText(String string) {
                        if(!bdid.equals("")){
                            String ss = StringProcess.codeMat(string);
                            oet.setText(ss);
                            presenter.saveFormList(bdid, bdmxBeanOutm);
                            //getRes(bdbid, ss);
                        }else{
                            showMsg("请先选择表单");
                        }
                    }
                });
        IntentFilter filter = new IntentFilter();
        filter.addAction(ScannerInterface.RES_ACTION);
        registerReceiver(customReceiver, filter);
        voiceUtils = new VoiceUtils(this);
        EventBus.getDefault().register(this);
        dataBean = (JDBeanNewOut.DataBean) getIntent().getSerializableExtra(PDApp.process);
        presenter.queryBD();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (customReceiver != null) {
            unregisterReceiver(customReceiver);
        }
        if (scanner != null) {
            scanner.setOutputMode(0);
        }
        EventBus.getDefault().unregister(this);
    }

    @Override
    public PageModel createModel() {
        return new PageModelImpl(this);
    }

    @Override
    public PageView createView() {
        return this;
    }

    @Override
    public PagePresent createPresenter() {
        return new PagePresent();
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    public void tip(String str) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                showMsg(str);
                voiceUtils.voiceWarn();
            }
        });
    }

    @Override
    public void tipBD(final BDBeanOut bdBeanOut) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if(bdBeanOut.getData()!=null && bdBeanOut.getData().size()>0){
                    pickerView = new OptionsPickerBuilder(BZActivity.this, new OnOptionsSelectListener() {
                        @Override
                        public void onOptionsSelect(int options1, int options2, int options3, View v) {
                            String tx = bdBeanOut.getData().get(options1).getName();
                            tvb.setText(tx);
                            //scanfFlag = false;
                            bdid = bdBeanOut.getData().get(options1).getPickerViewId();
                            list.clear();
                            itemAdapter = new ItemAdapter( BZActivity.this,list);
                            listView.setAdapter(itemAdapter);
                            presenter.queryBDMX(bdid);
                        }
                    })
                            .setTitleText("选择表单")
                            .setContentTextSize(20)//设置滚轮文字大小
                            .setTitleSize(20)
                            .setSubCalSize(20)
                            .setDividerColor(Color.LTGRAY)//设置分割线的颜色
                            .setSelectOptions(0)//默认选中项
                            .setBgColor(Color.WHITE)
                            .setTitleBgColor(getResources().getColor(R.color.white))
                            .setTitleColor(getResources().getColor(R.color.black))
                            .setCancelColor(getResources().getColor(R.color.gray_high))
                            .setSubmitColor(getResources().getColor(R.color.blue))
                            .setTextColorCenter(getResources().getColor(R.color.black))
                            .setSubmitText("确定")
                            .setCancelText("取消")
                            .isRestoreItem(true)//切换时是否还原，设置默认选中第一项。
                            .isCenterLabel(false) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
                            .setOutSideColor(0x2A2A2A4F) //设置外部遮罩颜色
                            .build();
                    pickerView.setPicker(bdBeanOut.getData());
                }
            }
        });
    }

    @Override
    public void tipBDBatch(BDBatchBeanOut bdBatchBeanOut) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                scanfFlag = true;
//                tvb.setEnabled(false);
//                tvb.setClickable(false);
//                for (int i = 0; i < lld.getChildCount(); i++) {
//                    View child = lld.getChildAt(i);
//                    child.setEnabled(false);
//                    child.setClickable(false);
//                }
                bdbid = bdBatchBeanOut.getData().getFormBatch();
                getRes(bdbid,oet.getText().toString());
            }
        });
    }

    @Override
    public void tipBDMX(BDMXBeanOut bdmxBeanOut) {
        lld.removeAllViews();
        for (int i = 0; i < bdmxBeanOut.getData().size(); i++) {
            bdmxBeanOut.getData().get(i).setKey(bdmxBeanOut.getData().get(i).getFormItemLabel());
            LinearLayout layout = new LinearLayout(mContext);
            layout.setOrientation(LinearLayout.HORIZONTAL);
            LinearLayout.LayoutParams LP_MM = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,LinearLayout.LayoutParams.WRAP_CONTENT);
            LP_MM.setMargins(20,20,20,0);
            layout.setLayoutParams(LP_MM);
            final int ti = i;
            if(bdmxBeanOut.getData().get(i).getFormItemType().equals("1")){
                LinearLayout.LayoutParams LP_WW1 = new LinearLayout.LayoutParams(320, LinearLayout.LayoutParams.WRAP_CONTENT);
                TextView tv = new TextView(mContext);
                tv.setText(bdmxBeanOut.getData().get(i).getFormItemLabel());
                tv.setTextSize(15);
                tv.setTextColor(mContext.getColor(R.color.black));
                tv.setLayoutParams(LP_WW1);
                layout.addView(tv);
                LinearLayout.LayoutParams LP_WW2 = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
                EditText ed = new EditText(mContext);
                ed.setId(bdmxBeanOut.getData().get(i).getFormID());
                ed.setBackgroundResource(R.mipmap.rect1);
                ed.setTextSize(15);
                LP_WW2.setMargins(10,0,0,0);
                ed.setPadding(10,0,0,0);
                ed.setLayoutParams(LP_WW2);
                ed.addTextChangedListener(new TextWatcher() {
                    @Override
                    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                    }

                    @Override
                    public void onTextChanged(CharSequence s, int start, int before, int count) {
                        bdmxBeanOut.getData().get(ti).setValue(s.toString());
                    }

                    @Override
                    public void afterTextChanged(Editable s) {
                    }
                });
                layout.addView(ed);
            }
            else if(bdmxBeanOut.getData().get(i).getFormItemType().equals("2")){
                LinearLayout.LayoutParams LP_WW1 = new LinearLayout.LayoutParams(320, LinearLayout.LayoutParams.WRAP_CONTENT);
                TextView tv = new TextView(mContext);
                tv.setText(bdmxBeanOut.getData().get(i).getFormItemLabel());
                tv.setTextSize(15);
                tv.setTextColor(mContext.getColor(R.color.black));
                tv.setLayoutParams(LP_WW1);
                layout.addView(tv);
                LinearLayout.LayoutParams LP_WW2 = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
                TextView tvv = new TextView(mContext);
                tvv.setBackgroundResource(R.mipmap.rect1);
                int iconBelowDrawableId = R.mipmap.icon_below;
                tvv.setCompoundDrawablesWithIntrinsicBounds(0, 0, iconBelowDrawableId, 0);
                tvv.setCompoundDrawablePadding(100);
                tvv.setTextSize(15);
                LP_WW2.setMargins(10,0,0,0);
                tvv.setPadding(10,0,0,0);
                tvv.setLayoutParams(LP_WW2);
                tvv.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        OptionsPickerView pickerView1 = new OptionsPickerBuilder(BZActivity.this, new OnOptionsSelectListener() {
                            @Override
                            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                                String tx = bdmxBeanOut.getData().get(ti).getListSelectList().get(options1).getSelectKey();
                                bdmxBeanOut.getData().get(ti).setValue(tx);
                                tvv.setText(tx);
                            }
                        })
                                .setTitleText("选择"+bdmxBeanOut.getData().get(ti).getFormItemLabel())
                                .setContentTextSize(20)//设置滚轮文字大小
                                .setTitleSize(20)
                                .setSubCalSize(20)
                                .setDividerColor(Color.LTGRAY)//设置分割线的颜色
                                .setSelectOptions(0)//默认选中项
                                .setBgColor(Color.WHITE)
                                .setTitleBgColor(getResources().getColor(R.color.white))
                                .setTitleColor(getResources().getColor(R.color.black))
                                .setCancelColor(getResources().getColor(R.color.gray_high))
                                .setSubmitColor(getResources().getColor(R.color.blue))
                                .setTextColorCenter(getResources().getColor(R.color.black))
                                .setSubmitText("确定")
                                .setCancelText("取消")
                                .isRestoreItem(true)//切换时是否还原，设置默认选中第一项。
                                .isCenterLabel(false) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
                                .setOutSideColor(0x2A2A2A4F) //设置外部遮罩颜色
                                .build();
                        pickerView1.setPicker(bdmxBeanOut.getData().get(ti).getListSelectList());
                        pickerView1.show();
                    }
                });

                layout.addView(tvv);
            }
            else if(bdmxBeanOut.getData().get(i).getFormItemType().equals("3")){
                LinearLayout.LayoutParams LP_WW1 = new LinearLayout.LayoutParams(320, LinearLayout.LayoutParams.WRAP_CONTENT);
                TextView tv = new TextView(mContext);
                tv.setText(bdmxBeanOut.getData().get(i).getFormItemLabel());
                tv.setTextSize(15);
                tv.setTextColor(mContext.getColor(R.color.black));
                tv.setLayoutParams(LP_WW1);
                layout.addView(tv);
                LinearLayout.LayoutParams LP_WW2 = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
                TextView tvv = new TextView(mContext);
                tvv.setBackgroundResource(R.mipmap.rect1);
                int iconBelowDrawableId = R.mipmap.icon_below;
                tvv.setCompoundDrawablesWithIntrinsicBounds(0, 0, iconBelowDrawableId, 0);
                tvv.setCompoundDrawablePadding(100);
                tvv.setTextSize(15);
                LP_WW2.setMargins(10,0,0,0);
                tvv.setPadding(10,0,0,0);
                tvv.setLayoutParams(LP_WW2);
                tvv.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Calendar calendar = Calendar.getInstance();
                        DatePickerDialog dialog = new DatePickerDialog(BZActivity.this, new DatePickerDialog.OnDateSetListener() {
                            @Override
                            public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
                                String desc = String.format("%d-%02d-%02d", year, month + 1, dayOfMonth);
                                bdmxBeanOut.getData().get(ti).setValue(desc);
                                tvv.setText(desc);
                            }
                        },
                                calendar.get(Calendar.YEAR),
                                calendar.get(Calendar.MONTH),
                                calendar.get(Calendar.DAY_OF_MONTH));
                        dialog.show();
                    }
                });
                layout.addView(tvv);
            }
            lld.addView(layout);
        }
        bdmxBeanOutm = bdmxBeanOut;
    }

    public void getRes(String id, final String code) {
        try {
            showProgress();
            Gson gson = new Gson();
            OkHttpClient client = new OkHttpClient.Builder()
                    .connectTimeout(SetConfig.getConnectTimeout(), TimeUnit.SECONDS)
                    .readTimeout(SetConfig.getReadTimeout(), TimeUnit.SECONDS)
                    .writeTimeout(SetConfig.getWriteTimeout(), TimeUnit.SECONDS)
                    .followRedirects(false)
                    .build();
            ApiYJ apisync = new Retrofit.Builder()
                    .baseUrl("http://" + SharedPreferencesManger.getHostName() + "/")
                    .client(client)
                    .build().create(ApiYJ.class);

            JieDianBeanIn jieDianBeanIn = new JieDianBeanIn();
            jieDianBeanIn.setAction("SY_UpdateCodeFormBatch");
            jieDianBeanIn.setCid(SharedPreferencesManger.getCid());
            jieDianBeanIn.setUserID(SharedPreferencesManger.getUid());
            jieDianBeanIn.setStoreID(SharedPreferencesManger.getStoreID());
            jieDianBeanIn.setFormBatch(id);
            jieDianBeanIn.setCodecc(code);

            RequestBody body = RequestBody.create(SetConfig.JSON, gson.toJson(jieDianBeanIn));
            final Call<ResponseBody> call = apisync.downLoad(body);
            Thread thread = new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        Response<ResponseBody> response = call.execute();
                        if (response.isSuccessful()) {
                            LogUtils.e(StringProcess.responsetoString(response.body()));
                            BaseBeanOut baseBeanOut = gson.fromJson(StringProcess.responsetoString(response.body()), BaseBeanOut.class);
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    if(baseBeanOut.getErrcode()==0){
                                        list.add(code);
                                        itemAdapter.notifyDataSetChanged();
                                    }
                                }
                            });
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    } finally {
                    }
                }
            });
            thread.start();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            hideProgress();
            return;
        }
    }

    public void delCode(String id, final String code) {
        try {
            showProgress();
            Gson gson = new Gson();
            OkHttpClient client = new OkHttpClient.Builder()
                    .connectTimeout(SetConfig.getConnectTimeout(), TimeUnit.SECONDS)
                    .readTimeout(SetConfig.getReadTimeout(), TimeUnit.SECONDS)
                    .writeTimeout(SetConfig.getWriteTimeout(), TimeUnit.SECONDS)
                    .followRedirects(false)
                    .build();
            ApiYJ apisync = new Retrofit.Builder()
                    .baseUrl("http://" + SharedPreferencesManger.getHostName() + "/")
                    .client(client)
                    .build().create(ApiYJ.class);

            JieDianBeanIn jieDianBeanIn = new JieDianBeanIn();
            jieDianBeanIn.setAction("SY_DeleteCodeFormBatch");
            jieDianBeanIn.setCid(SharedPreferencesManger.getCid());
            jieDianBeanIn.setUserID(SharedPreferencesManger.getUid());
            jieDianBeanIn.setStoreID(SharedPreferencesManger.getStoreID());
            jieDianBeanIn.setFormBatch(id);
            jieDianBeanIn.setCodecc(code);

            RequestBody body = RequestBody.create(SetConfig.JSON, gson.toJson(jieDianBeanIn));
            final Call<ResponseBody> call = apisync.downLoad(body);
            Thread thread = new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        Response<ResponseBody> response = call.execute();
                        if (response.isSuccessful()) {
                            LogUtils.e(StringProcess.responsetoString(response.body()));
                            BaseBeanOut baseBeanOut = gson.fromJson(StringProcess.responsetoString(response.body()), BaseBeanOut.class);
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    if(baseBeanOut.getErrcode()==0){
                                        list.remove(code);
                                        itemAdapter.notifyDataSetChanged();
                                    }
                                }
                            });
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    } finally {
                    }
                }
            });
            thread.start();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            hideProgress();
            return;
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onBaseMessageEvent(MessageBus messageBus) {
        String code = list.get(messageBus.getIndex());
        delCode(bdbid,code);
    }

    @OnClick({R.id.iv_title_left, R.id.tvb,R.id.bt1, R.id.bt2, R.id.bt3})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_title_left:
                finish();
                break;
            case R.id.tvb:
                pickerView.show();
                break;
            case R.id.bt1:
                if(bdmxBeanOutm==null){
                    showMsg("当前无表单数据");
                    return;
                }
                list.clear();
                itemAdapter = new ItemAdapter( BZActivity.this,list);
                listView.setAdapter(itemAdapter);
                presenter.saveFormList(bdid, bdmxBeanOutm);
                break;
            case R.id.bt2:
                tvb.setEnabled(true);
                tvb.setClickable(true);
                for (int i = 0; i < lld.getChildCount(); i++) {
                    View child = lld.getChildAt(i);
                    child.setEnabled(true);
                    child.setClickable(true);
                }
                //scanfFlag = false;
                bdmxBeanOutm = null;
                list.clear();
                itemAdapter = new ItemAdapter( BZActivity.this,list);
                listView.setAdapter(itemAdapter);
                lld.removeAllViews();
                break;
            case R.id.bt3:
//                if(!scanfFlag){
//                    showMsg("保存表单后才能扫描");
//                    return;
//                }
                if(bdid.equals("")){
                    showMsg("请先选择表单");
                    return;
                }
                if(oet.getText().toString().length()==0){
                    showMsg("数码不能为空");
                    return;
                }
                presenter.saveFormList(bdid, bdmxBeanOutm);
                break;
        }
    }
}
